﻿using AuthCenter.API.Application.Command.Account;
using AuthCenter.Domain;
using AuthCenter.Domain.Account;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MD5Hash;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace AuthCenter.API.Application.Handler.Account
{
    public class CreateAccountHandler : IRequestHandler<CreateAccountCommand, APIResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<LogModel> logRepo;
        private readonly IMapper mapper;

        public CreateAccountHandler(IBaseRepository<AccountModel> accountRepo,
                                    IBaseRepository<LogModel> logRepo,
                                    IMapper mapper)
        {
            this.accountRepo = accountRepo;
            this.logRepo = logRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(CreateAccountCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = accountRepo.GetAll().FirstOrDefault(x=>x.Name == request.Name);
            if (res != null)
            {
                result.Message = "已拥有该用户名";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var model = mapper.Map<AccountModel>(request);
            model.Id = YitIdHelper.NextId();
            model.PassWord = request.PassWord.GetMD5();
            model.CreateName = request.LoginName;
            model.CreateDate = DateTime.Now;
            LogModel log = new LogModel()
            {
                Id = YitIdHelper.NextId(),
                LogContent = $"用户添加成功,操作人{request.LoginName}"
            };
            int r = 0;
            int r1 = 0;
            using(TransactionScope tran = new TransactionScope())
            {
                try
                {
                    r = accountRepo.AddAsync(model).Result;
                    r1 = logRepo.AddAsync(log).Result;
                    tran.Complete();
                }
                catch (Exception)
                {
                    throw;
                }
            }
            if (r > 0)
            {
                result.Message = "用户添加成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "用户添加失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
